package com.example.common;

import com.fasterxml.jackson.databind.ObjectMapper;
import org.dom4j.io.SAXReader;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import java.io.File;
import java.io.InputStream;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 获取公司信息
 */
public class CompanyConfigUtil {

    public static Map<String, String> getCompanyInfoByInvOwner(String invOwner) {
        Map<String, String> result = new HashMap<>();
        try {
            InputStream is = CompanyConfigUtil.class.getClassLoader().getResourceAsStream("config/company-config.xml");
            DocumentBuilder builder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
            Document doc = builder.parse(is);
            NodeList nodeList = doc.getElementsByTagName("company");

            for (int i = 0; i < nodeList.getLength(); i++) {
                Element companyElem = (Element) nodeList.item(i);
                String owner = companyElem.getAttribute("id");

                if (owner != null && owner.equals(invOwner)) {
                    result.put("name", getTagValue(companyElem, "name"));
                    result.put("code", getTagValue(companyElem, "code"));
                    result.put("opter", getTagValue(companyElem, "opter"));
                    result.put("opterName", getTagValue(companyElem, "opterName"));
                    result.put("ak", getTagValue(companyElem, "ak"));
                    result.put("sk", getTagValue(companyElem, "sk"));
                    break;
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }


    private static String getTagValue(Element element, String tagName) {
        NodeList nodeList = element.getElementsByTagName(tagName);
        if (nodeList.getLength() > 0) {
            Node node = nodeList.item(0);
            return node.getTextContent();
        }
        return null;
    }
}
